$.ziPOST = function(action,data,callback){
	$.post('ajax.php?action='+action,data,callback,'json');
}

$.ziGET = function(action,data,callback){
	$.get('ajax.php?action='+action,data,callback,'json');
}

function htmlEncode(value){
	return $('<div/>').text(value).html();
}

// this function must be used for MySQL query return results.
function htmlDecode(value){
	return $('<div/>').html(value).text();
}

function preload(arrayOfImages) {
    $(arrayOfImages).each(function(){
        $('<img/>')[0].src = this;
        // Alternatively you could use:
        // (new Image()).src = this;
    });
}

var aDay = new Date( 1970, 0, 2 );

function render_timestamp( date_string, time_zone ) {
	if( date_string == undefined ) {
		date_string = "2011-12-06 10:13:53";
	}
	if( time_zone == undefined ) {
		time_zone = "GMT";
	}
	
	var temps  = date_string.split(' ');
	var ss0    = temps[0].split('-');
	var ss1    = temps[1].split(':');
	var date   = new Date( ss0[0], ss0[1] - 1, ss0[2], ss1[0], ss1[1], ss1[2] );
	var res = "";
	
	var diff   = new Date( Date.now() - date );
	
	if( Date.now() < date || diff > aDay ) {
		res = "on " + render_month( date.getMonth() ) + " " + date.getDate() + ", " + date.getFullYear();
	} else if( diff.getHours() > 0 ) {
		res = diff.getHours() + " hours ago";
	} else if( diff.getMinutes() > 3 ) {
		res = diff.getMinutes() + " minutes ago";
	} else {
		res = "just now";
	}
	return res; 
}

function render_chat_timestamp( date_string, time_zone ) {
	if( date_string == undefined ) {
		date_string = "2011-12-06 10:13:53";
	}
	if( time_zone == undefined ) {
		time_zone = "GMT";
	}
	
	var temps  = date_string.split(' ');
	var ss0    = temps[0].split('-');
	var ss1    = temps[1].split(':');
	var date   = new Date( ss0[0], ss0[1] - 1, ss0[2], ss1[0], ss1[1], ss1[2] );
	var res = "";
	
	var diff   = new Date( Date.now() - date );
	
	if( Date.now() < date || diff > aDay ) {
		res = render_month( date.getMonth() ) + " " + date.getDate() + ", " + date.getFullYear();
	} else if( diff.getHours() > 0 ) {
		res = diff.getHours() + " hours ago";
	} else if( diff.getMinutes() > 3 ) {
		res = diff.getMinutes() + " minutes ago";
	} else {
		res = "just now";
	}
	return res; 
}

// mon is an integer between 0-11
// return a 3-char-string to represent the given input month. 
function render_month( mon ) {
	var res;
	switch( mon ) {
		case 0:
			res = "Jan";
			break;
		case 1:
			res = "Feb";
			break;
		case 2:
			res = "Mar";
			break;
		case 3:
			res = "Apr";
			break;
		case 4:
			res = "May";
			break;
		case 5:
			res = "Jun";
			break;
		case 6:
			res = "Jul";
			break;
		case 7:
			res = "Aug";
			break;
		case 8:
			res = "Sep";
			break;
		case 9:
			res = "Oct";
			break;
		case 10:
			res = "Nov";
			break;
		case 11:
			res = "Dec";
			break;
		default:
			res = "Wrong input";	
	}
	return res;
}

function tagAction(target,action){
    var targetTag = target.parent();
    var otherNebulas = $('#all-nebulas');
    var taggedNebulas = $('#nebula-content');
    var nid = targetTag.attr('nid');
    var icon = targetTag.attr('icon');
    var name = targetTag.attr('name');
    var profv = targetTag.attr('profv');
    if(action=="untag"){
        target.parent().parent().append('<div id="tagEx_'+nid+'" class="tagExpand" style="color:#777;float:right;display:none;"><a class="confirm-tag isfocus">[Yes]</a><a class="cancel-tag isfocus">[No]</a></div>');
        $('#tagEx_'+nid).slideDown('fast',function(){
            //confirm untag event
            var confirmObj = $('.confirm-tag');
            confirmObj.unbind('click');
            confirmObj.bind('click',function(){
                target.html('[-ing]');
                //swtich the user options
                $('#newPost_'+nid).hide();
                $('#newGalaxy_'+nid).hide();
                $('#tagnebulaFun_'+nid).html("Requesting...");
                $('#tagnebulaFun_'+nid).css('display','block');
                $.ziGET('untag_nebula',{
                    'nid': nid
                },function(r){
                    if(r==1){
                        var tagInfo = {
                            'nid': nid,
                            'icon': icon,
                            'name' :name,
                            'profv': profv
                        };
                        var removeItem = commonInfo.render('other-topNebula',tagInfo);
                        otherNebulas.append(removeItem);
                        $('#tagnebulaFun_'+nid).html('Tag Nebula');
                        targetTag.parent().fadeOut('fast',function(){
                            targetTag.parent().remove();
                            $('#tagEx_'+nid).remove();
                            if(taggedNebulas.children().length==0){
                                taggedNebulas.html('You have no tagged nebuals');
                            }
                        });

                    }
                });
            });
            //cancel untag event
            var cancelObj = $('.cancel-tag');
            cancelObj.unbind('click');
            cancelObj.bind('click',function(){
                $('#tagEx_'+nid).slideUp('fast',function(){
                    $('#tagEx_'+nid).remove();
                });
            });
        });
        
    }
    if(action=="tag"){
        target.parent().parent().append('<div id="tagEx_'+nid+'" class="tagExpand" style="color:#777;float:right;display:none;"><a class="confirm-tag isfocus">[Yes]</a><a class="cancel-tag isfocus">[No]</a></div>');
        $('#tagEx_'+nid).slideDown('fast',function(){
            //confirm tag event
            var confirmObj = $('.confirm-tag');
            confirmObj.unbind('click');
            confirmObj.bind('click',function(){
                target.html('[+ing]');
                //swtich the user options
                $('#tagnebulaFun_'+nid).html("Requesting...");
                
                $.ziGET('tag_nebula',{
                    'tags': nid
                },function(r){
                    if(r==1){
                        var removeInfo = {
                            'nid': nid,
                            'icon': icon,
                            'name' :name,
                            'profv': profv
                        };
                        $('#newPost_'+nid).css('display','block');
                        $('#newGalaxy_'+nid).css('display','block');
                        $('#tagnebulaFun_'+nid).hide();
                        var addItem = commonInfo.render('tag-topNebula',removeInfo);
                        if(taggedNebulas.children().length==0){
                            taggedNebulas.html('');
                        }
                        taggedNebulas.append(addItem);
                        targetTag.parent().fadeOut('fast',function(){
                            targetTag.parent().remove();
                            $('#tagEx_'+nid).remove();
                        });
                    }
                });
            });
            //cancel tag event
            var cancelObj = $('.cancel-tag');
            cancelObj.unbind('click');
            cancelObj.bind('click',function(){
                $('#tagEx_'+nid).slideUp('fast',function(){
                    $('#tagEx_'+nid).remove();
                });
            });
        });
    }
}

function get_tagged_nebulas(num, contentBlock, uid, inProfile){
	var iconBlock = contentBlock.find($('.nebula ul'));
	var outBlock  = iconBlock.parent();
	iconBlock.html('<div class="loading section-padding"><img src="img/loading.gif"/></div>');
	$.ziGET('nebulas_for_uid', {'uid':uid}, function(r) {
		iconBlock.html("");
        if(uid==$('#profile-container').attr('cuid')||inProfile){
            var markup="";
            num = Math.min(num, r.length);
            for(var i = 0; i < num; i++) {
                var markup = commonInfo.render('tagged-nebula', r[i]);
            	var element = $(markup).appendTo(iconBlock);
            	var e = element.find('#tagID-'+r[i]['nid'])
            	var markup_label = commonInfo.render('tagged-nebula-label', r[i]);
            	var el = $(markup_label).appendTo(outBlock);
            	var e_left = e.position().left+2;
            	var e_top = e.position().top;
            	var el_bias = el.width()/2-10;
            	el.css("left", (e_left-el_bias)+"px");
            	e.bind("mouseenter", function(){
            		var nid = $(this).attr("id");
            		nid = nid.split("-")[1];
            		outBlock.find('#tagLabel-'+nid).show();
            	});
            	e.bind("mouseleave", function(){
            		var nid = $(this).attr("id");
            		nid = nid.split("-")[1];
            		outBlock.find('#tagLabel-'+nid).hide();
            	});
            }
            if(r.length>num){
                contentBlock.find($('.showall')).html("Show all");
            }
            if(num == 0){
                iconBlock.html('<div class="section-padding" style="text-align: center;">Currently None</div>')
            }
        }

	});
}

function get_recent_posts( num, contentBlock, uid, inProfile) {
	contentBlock.html( '<div class="loading section-padding"><img src="img/loading.gif"/></div>' );
	$.ziGET('recent_posts', {'max_num':num,'uid':uid}, function(r) {
        if(uid==$('#profile-container').attr('cuid')||inProfile){
            var markup="";
            for(var i = 0; i < r.length; i++) {
                markup = markup+commonInfo.render('recent-post', r[i]);
            }
            contentBlock.html(markup);
        }
	});
}

function get_recent_galaxies( num, contentBlock, uid, inProfile) {
	contentBlock.html( '<div class="loading section-padding"><img src="img/loading.gif"/></div>' );
	$.ziGET('recent_galaxies', {'max_num':num,'uid':uid}, function(r) {
        if(uid==$('#profile-container').attr('cuid')||inProfile){
            var markup="";
            for(var i = 0; i < r.length; i++) {
                markup = markup+commonInfo.render('recent-galaxy', r[i]);
            }
            contentBlock.html(markup);
        }
    });
}

function render_top_bar(){
    //need to be placed in some file that would be commonly refed.
    var top_bar = $('#topBar');
    var top_bar_content = commonInfo.render('top-bar',session_user_info);
    top_bar.html(top_bar_content);
    var otherNebulas = $('#all-nebulas');
    var taggedNebulas = $('#nebula-content');
    taggedNebulas.html('Loading');
    otherNebulas.html('Loading');
    taggedNebulas.css('display','block');
    otherNebulas.css('display','none');
    var uid = session_user_info['uid'];
    var isFirstRead = true;
    $('.headlink').hover(function(){
        var id = $(this).attr('href');
        $(id).css('display','block');
        //display the tagged nebuals
        if(id=="#nebulas-top"){
            if(isFirstRead){
                isFirstRead = false;
                initTopBarNebula(uid);                
            
                //bind tag event
                otherNebulas.find('.addFun').unbind('click');
                otherNebulas.find('.addFun').click(function(){
                    tagAction($(this),"tag");
                });
                //bind untag event
                taggedNebulas.find('.removeFun').unbind('click');
                taggedNebulas.find('.removeFun').click(function(){
                    tagAction($(this),"untag");
                });
                //show user's tag nebuals
                $('#my-nebulas').unbind('click');
                $('#my-nebulas').click(function(){
                    otherNebulas.fadeOut('fast',function(){
                        $('#my-nebulas').css('color','#7CC0CB');
                        $('#top-nebulas').css('color','#777');
                        taggedNebulas.fadeIn('fast',function(){
                            //bind untag event
                            taggedNebulas.find('.removeFun').unbind('click');
                            taggedNebulas.find('.removeFun').click(function(){
                                tagAction($(this),"untag");
                            });
                        });
                    })
                })

                //show all the other nebuals
                $('#top-nebulas').unbind('click');
                $('#top-nebulas').click(function(){
                    taggedNebulas.fadeOut('fast',function(){
                        $('#my-nebulas').css('color','#777');
                        $('#top-nebulas').css('color','#7CC0CB');
                        otherNebulas.fadeIn('fast',function(){
                            //bind tag event
                            otherNebulas.find('.addFun').unbind('click');
                            otherNebulas.find('.addFun').click(function(){
                                tagAction($(this),"tag");
                            });
                        });
                    });
                });
            }
        }
        if(id=="#user-top"){            
            $('#user-pull-down').show();
            var logoutBtn = $('#user-logout');
            logoutBtn.unbind('click');
            logoutBtn.bind('click',function(){
                $.ziGET('logout', 0, function(r){
					window.location.reload();
                });
            })
        }
        
    },function(){
        $('.tagExpand').remove();
        $('.pull-down').hide();
    });


}

function initTopBarNebula(uid){
    
    var otherNebulas = $('#all-nebulas');
    var taggedNebulas = $('#nebula-content');
    //show tag nebula
    $.ziGET('nebulas_for_uid',{
        'uid':uid
    },function(r){
        var topNebulas = $('#nebula-content');
        if(r.length>0){
            topNebulas.html('');
            for(var i=0;i<r.length;i++){
                var profv = r[i]['profv'];
                profv = profv.split(" ");
                profv = profv[(r[i]['nid'])];
                var dotIndex = profv.indexOf('.');
                profv = profv.substring(0,dotIndex+2);
                var addInfo = {
                    'nid':r[i]['nid'],
                    'name':r[i]['name'],
                    'icon':r[i]['icon'],
                    'profv':profv
                }
                var nebulasItem = commonInfo.render('tag-topNebula',addInfo);
                topNebulas.append(nebulasItem);
            }
            //bind untag event
            topNebulas.find('.removeFun').unbind('click');
            topNebulas.find('.removeFun').click(function(){
                tagAction($(this),"untag");
            });
        }
        else{
            topNebulas.html('You have no tagged nebuals');
        }
        //show other nebulas
        $.ziGET('all_nebulasv2',{},function(r){
            otherNebulas.html('');
            for(var i=0;i<r.length;i++){
                var profv = r[i]['profv'];
                profv = profv.split(" ");
                profv = profv[(r[i]['nid'])];
                var addInfo = {
                    'nid':r[i]['nid'],
                    'name':r[i]['name'],
                    'icon':r[i]['icon'],
                    'profv':profv
                }
                
                var nebulaInfo = commonInfo.render('other-topNebula',addInfo);
                otherNebulas.append(nebulaInfo);
            }
            //hide the tagged nebuals
            taggedNebulas.children().find('.nebula-item').each(function(){
                var nid = $(this).attr('nid');
                $('#other-'+nid).remove();
            })
            //bind tag event
            otherNebulas.find('.addFun').unbind('click');
            otherNebulas.find('.addFun').click(function(){
                tagAction($(this),"tag");
            });
        });
    });
}
function reSizeAvatar(avtarTag){
    avtarTag.each(function(){
        $(this).load(function(){
            var avatarSrc=$(this).attr('src');
            var newAvatar = new Image();
            newAvatar.src = avatarSrc;
            var width = newAvatar.width;
            var height = newAvatar.height;
            if(width>height){
                $(this).css('width','100%');
                $(this).show();
            }
            else{
                $(this).css('height','100%');
                $(this).show();
            }
        })
    })
}
function reSizeImg(imgTag){
    imgTag.each(function(){
        $(this).load(function(){
            var imgSrc = $(this).attr('src');
            var newImg = new Image();
            newImg.src = imgSrc;
            var width = newImg.width;
            //large images
            if(width>450){
                $(this).css("width","100%");
            }
        });
    });
}

function extentPostLength(proc_string){
    var tagContent_length = 0;
    //uncount the tag content
    var img_urlTag = proc_string.match(/[<a>].*href.*[<\a>]/g);
    var flashTag = proc_string.match(/[<iframe>].*src.*[>]/g);
    if(img_urlTag!=null){
        for(var i=0;i<img_urlTag.length;i++){
            tagContent_length+=(img_urlTag[i].length);
        }
    }
    if(flashTag!=null){
        for(var j=0;i<flashTag.length;i++){
            tagContent_length+=(flashTag[j].length);
        }
    }
    return tagContent_length;
}
var commonInfo = {
    data: {
		center_pos	: {centerX : 165, centerY: 300}
	},
    render:function(template,params){
        var arr = [];
        switch(template){
            case 'top-bar':
                arr=[
                    '<div id="topBarContent">\n\
                        <img id="topbar-logo" src="img/logo4.png" />\n\
                        <div id="topBarNav"><ul id="frame-nav-top" class="frame-nav">\n\
                            <li href="#home" ><a id="home" class="pull-menu" href="./profile.php">Home</a></li>\n\
                            <li href="#circle-top"><a id="circle" class="pull-menu" href="./circle.php">Circles</a></li>\n\
                            <li class="headlink" href="#nebulas-top"><a id="nebulas" class="pull-menu">Nebulas <span class="W_arr_d"><em class="b1"></em><em class="b2"></em><em class="b3"></em></span></a>\n\
                                <div id="nebulas-top" class="pull-down" style="display:none;"><div class="top-fun"><a id="my-nebulas" class="isfocus" style="float:left; color:#7CC0CB;">[My nebulas]</a><a id="top-nebulas" class="isfocus" style="float:right;color:#777;">[Add More]</a></div>\n\
                                    <div class="top-border"></div>\n\
                                    <div id="nebula-content"></div>\n\
                                    <div id="all-nebulas"style="height:40px;"></div>\n\
                            </li><li id="user-pop" class="headlink" href="#user-top">\n\
                                <div style="height:28px min-width:10px;float:left;margin-top:-8px;padding-right:6px">\n\
                                <img style="height:28px" src="',params['avatar'],'"/></div>\n\
                                <a>',params['username'],' <span class="W_arr_d"><em class="b1"></em><em class="b2"></em><em class="b3"></em></span></a>\n\
                                <div id="user-pull-down" class="pull-down" style="display:none;">',
                                '<div class="user-menu"><a id="user-setting" href="./settings_basics.php" style="text-decoration:none;">',
                                    '<img width="16" height="16" alt="setting" src="./img/setting.png"></a>',
                                    '<a href="./settings_basics.php" class="user-menu-title">Settings</a></div>',
                                '<div class="user-menu"><a href="./circlefile.php?uid=',session_user_info['uid'],'" style="text-decoration: none;">',
                                    '<img width="16" height="16" alt="setting" src="./img/profile.png"></a>',
                                    '<a href="./circlefile.php?uid=',session_user_info['uid'],'" class="user-menu-title">Profile</a></div>',
                                '<div class="user-menu"><a id="user-logout" href="./ajax.php?action=logout" style="text-decoration: none;">',
                                    '<img width="16" height="16" alt="setting" src="./img/logout.png"></a>',
                                    '<a href="./ajax.php?action=logout" class="user-menu-title">Log out</a></div>',
                                '</li>\n\
                                </ul></div></div>'
                ]
                break;
           case 'tag-topNebula':
               arr=[
                   '<div><div id="tag-',params['nid'],'"class="nebula-item" name="',params['name'],'" icon="',params['icon'],'" nid="',params['nid'],'" profv="',params['profv'],'"><a href="./topics.php?nid=',params['nid'],'"><img src="',params['icon'],'" style="height:23px;width:23px;float:left;"></a>\n\
                    <a class="topneb-title" href="./topics.php?nid=',params['nid'],'">',params['name'],': </a>\n\
                    <a style="float:left;margin-top: 2.5px;">',params['profv'],'</a>\n\
                    <a class="removeFun tag-op isfocus" style="float:right" title="remove tag">[-]</a></div></div>'
               ];
               break;
           case 'other-topNebula':
               arr=[
                   '<div><div id="other-',params['nid'],'"class="nebula-item" name="',params['name'],'" icon="',params['icon'],'" nid="',params['nid'],'" profv="',params['profv'],'"><a href="./topics.php?nid=',params['nid'],'"><img src="',params['icon'],'" style="height:23px;width:23px;float:left;"></a>\n\
                    <a class="topneb-title" href="./topics.php?nid=',params['nid'],'">',params['name'],': </a>\n\
                    <a style="float:left;margin-top: 2.5px;">',params['profv'],'</a>\n\
                    <a class="addFun tag-op isfocus" style="float:right" title="add tag">[+]</a></div></div>'
               ];
               break;
           case 'tagged-nebula':
                arr=[
                '<a href=./topics.php?nid=',params['nid'],'><li id="tagID-',params['nid'],'"><img style="width:20px; height:20px;" src="',params['icon'],'"/></li></a>'
                ];
                break;
		   case 'tagged-nebula-label':
		   		arr=[
		   		'<div class="tagLabel" id="tagLabel-',params['nid'],'"><div class="label-name roundedS">',params['name'],'</div><div class="label-tri"></div></div>'
		   		];
		   		break;
           case 'recent-post':
				if( params['title'].length > 25 ) {
					params['title'] = params['title'].substr(0, 25) + "...";
				}
				arr=[
					'<li><span class="title"><a href = "./topics.php?nid=', params['default_nid'],'&pid=', params['pid'],'">', params['title'], '</a></span><span class="recent-info">',
                    '<a href="./circlefile.php?uid=',params['post_uid'],'">', params['username'],'</a> ',
					render_timestamp( params['ts'] ), '</span></li>'
				];
				break;
           case 'recent-galaxy':
				if( params['title'].length > 25 ) {
					params['title'] = params['title'].substr(0, 25) + "...";
				}
				arr=[
					'<li><span class="title">', params['title'], '</span><span class="recent-info">',
                    '<a href="./circlefile.php?uid=',params['galaxy_uid'],'">',params['username'],'</a> ',
					render_timestamp( params['ts'] ), '</span></li>'
				];
				break;
           case 'self-info':
				var birth = params['birthday'];
				var birthYear = birth.split('-')[0];
				if(params['gender']=="x")
					var gender = "Neither";
				else
					var gender = params['gender'];
				arr=[
					'<ul style="list-style-type: none;"><li>Sex: ',gender,'</li>',
					'<li>Age: ',getAge(birthYear),'</li>',
					(params['description'])?'<li>Description: '+params['description']+'</li></ul></ul>':'<li>Description: None</li></ul></ul>'
				];
				break;
        }      
        return arr.join('');
    }
}


function getAge(birthYear){
	var curTime = new Date();
	var curYear = curTime.getFullYear();
	return curYear-birthYear;
}

function get_user_info(contentBlock){
	$.ziGET('getSelfInfo', {}, function(r){
		contentBlock.html(commonInfo.render('self-info', r[0]))
	});
}